<template>
  <div>
    <el-row type="flex" justify="start"><el-checkbox v-model="isCheckAll" :indeterminate="isIndeterminate" @change="handleAllChange">全选</el-checkbox></el-row>
    <el-row type="flex" justify="start" class="my-region" style="margin-top: 0.8rem">
      <el-checkbox-group v-model="checkedList" @change="onChange">
        <el-checkbox v-for="(item, index) in checkList" :key="index" :label="index" :span="8" class="item" style="padding:0 .2rem .2rem 0; width:120px;">{{ item[column] }}</el-checkbox>
      </el-checkbox-group>
    </el-row>
  </div>
</template>
<script>

export default {
  model: {
    prop: 'checkList',
    event: 'return'
  },
  props: {
    checkList: {
      type: Array,
      default: () => []
    },
    column: {
      type: String,
      default: 'name'
    }
  },
  data() {
    return {
      isCheckAll: false,
      isIndeterminate: false,
      checkedList: []
    }
  },
  watch: {
    'checkList'() {
      this.init()
      console.log('checkList===>', this.checkList)
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.isCheckAll = false
      this.isIndeterminate = false
      this.checkedList = []
      this.checkList.forEach((elem, index) => {
        if (elem['checked']) {
          this.checkedList.push(index)
        }
      })
    },
    onChange(val) {
      const index = val.length
      this.isCheckAll = index === this.checkList.length
      this.isIndeterminate = index > 0 && index < this.checkList.length
      this.onReturn()
    },
    handleAllChange(val) {
      this.checkList.forEach(elem => {
        this.$set(elem, 'checked', val)
      })
      this.checkedList = val ? this.checkList : []
      this.isIndeterminate = false
      this.onReturn()
    },
    onReturn() {
      this.checkList.forEach(elem => {
        elem['checked'] = false
      })
      this.checkedList.forEach(elem => {
        this.$set(this.checkList[elem], 'checked', true)
      })
      this.$emit('return', this.checkList)
    }
  }
}
</script>
